<?php

namespace App\Http\Controllers\API;

use App\Http\Requests\API\CreateProductAPIRequest;
use App\Http\Requests\API\UpdateProductAPIRequest;
use App\Models\Product;
use App\Repositories\ProductRepository;
use App\Services\AliService;
use Illuminate\Http\Request;
use App\Http\Controllers\AppBaseController;
use InfyOm\Generator\Criteria\LimitOffsetCriteria;
use Prettus\Repository\Criteria\RequestCriteria;
use Response;

/**
 * Class ProductController
 * @package App\Http\Controllers\API
 */
class ProductAPIController extends AppBaseController
{
    /** @var  ProductRepository */
    private $productRepository;
    private $server;

    public function __construct(Request $request)
    {
        $this->productRepository = app(ProductRepository::class);
        $this->server = new AliService();
    }

    /**
     * @api {get} /api/products 获取产品列表
     * @apiVersion 1.0.0
     * @apiDescription
     * @apiGroup Product
     *
     * @apiParam   {int} [page_limit=100] 每页显示的个数 默认为100.
     * @apiParam   {int} [page=1] 默认显示第一页
     * @apiParam   {string} [ProductName] 根据名字查找
     * @apiParam   {string} [desc] 降序的字段
     * @apiParam   {string} [asc] 升序的字段
     *
     * @apiHeader {String} Accept=application/json
     * @apiHeader {String} Authorization Bearer xxxxx
     *
     * @apiSampleRequest api/products
     * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     * {
     * "code": 0,
     * "msg": "Products retrieved successfully",
     * "data": {
     * "current_page": 1,
     * "data": [
     * {
     * "id": 1,
     * "ProductKey": "VjkhzB7u4fE",
     * "ProductDesc": "Create Product",
     * "CatId": 10000,
     * "ProductName": "TestProduct",
     * "created_at": "2017-12-01 09:26:49",
     * "updated_at": "2017-12-01 09:26:49",
     * "deleted_at": null
     * }
     * ],
     * "first_page_url": "http://localhost:8000/api/products?page=1",
     * "from": 1,
     * "last_page": 1,
     * "last_page_url": "http://localhost:8000/api/products?page=1",
     * "next_page_url": null,
     * "path": "http://localhost:8000/api/products",
     * "per_page": 100,
     * "prev_page_url": null,
     * "to": 1,
     * "total": 1
     * }
     * }
     **/
    public function index(Request $request)
    {
        $this->productRepository->pushCriteria(new RequestCriteria($request));
        $this->productRepository->pushCriteria(new LimitOffsetCriteria($request));
        $page_limit = empty($request->input('page_limit')) ? 100 : $request->input('page_limit');


        $products = $this->productRepository->getProductList($page_limit, $request->input());

        return $this->success($products->toArray(), 'Products retrieved successfully');
    }

    /**
     * @api {post} api/products  创建产品
     * @apiVersion 1.0.0
     * @apiName store
     * @apiGroup Product
     *
     * @apiParam   {long} CatId 产品类型id
     * @apiParam   {string} ProductName 名称
     * @apiParam   {string} ProductDesc 描述
     * * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     *  {
     * RequestId:8AE93DAB-958F-49BD-BE45-41353C6DEBCE,
     * Success:true,
     * ProductInfo:{
     * ProductKey:...,
     * CatId:56000,
     * ProductName:工业产品
     * }
     * }
     */
    public function store(CreateProductAPIRequest $request)
    {
        $input = $request->all();
        $rules = array("CatId" => "required",
            "ProductName" => "required",
            "ProductDesc" => "required"
        );
        $messages = array("CatId.required" => "catId为空",
            "ProductName.required" => "产品名称",
            "ProductDesc.required" => "描述");
        $result = $this->validate($input, $rules, $messages);
        if ($result["code"] != 0) {
            return $this->fail(self::VALIDATE_ERROR, $result["errors"]);
        }

        $res = $this->server->createProduct($input['CatId'], $input['ProductName'], $input['ProductDesc']);
        if ($res->Success) {
            $input['ProductKey'] = $res->ProductInfo->ProductKey;
            $products = $this->productRepository->create($input);
            return $this->success($products->toArray(), 'Product saved successfully');
        } else {
            return $this->fail(-1, $res->ErrorMessage);
        }
    }

    /**
     * Display the specified Product.
     * GET|HEAD /products/{id}
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        /** @var Product $product */
        $product = $this->productRepository->findWithoutFail($id);

        if (empty($product)) {
            return $this->sendError('Product not found');
        }

        return $this->sendResponse($product->toArray(), 'Product retrieved successfully');
    }

    /**
     * @api {put} api/products/:id  修改产品
     * @apiVersion 1.0.0
     * @apiName store
     * @apiGroup Product
     * @apiParam   {long} [CatId] 产品类型id
     * @apiParam   {string} [ProductName] 名称
     * @apiParam   {string} [ProductDesc] 描述
     * * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     * {
     * "code": 0,
     * "msg": "ok",
     * "data": {
     * "id": 1,
     * "ProductKey": "Sdv5hMAlAFx",
     * "ProductDesc": "CCDD",
     * "CatId": 10000,
     * "ProductName": "继电器",
     * "created_at": "2017-12-04 18:10:44",
     * "updated_at": "2017-12-06 17:15:22",
     * "deleted_at": null
     * }
     * }
     */
    public function update($id, UpdateProductAPIRequest $request)
    {
        $input = $request->all();
        $product = $this->productRepository->findWithoutFail($id);

        if (empty($product)) {
            return $this->fail(-1, 'Product not found');
        }

        $input['ProductKey'] = $product['ProductKey'];

        $res = $this->server->updateProduct($input);
        if ($res->Success) {
            $product = $this->productRepository->update($input, $id);
            return $this->sendResponse($product->toArray(), 'Product updated successfully');
        } else {
            return $this->fail(-1, $res->ErrorMessage);
        }

    }

    /**
     * @api {delete} api/products/:id  删除产品
     * @apiVersion 1.0.0
     * @apiName store
     * @apiGroup Product
     * * @apiSuccessExample {json} Success-Response:
     *     HTTP/1.1 200 OK
     * {
     * "code": 0,
     * "msg": "ok",
     * "data": {
     * }
     */
    public function destroy($id)
    {
        /** @var Product $product */
        $product = $this->productRepository->findWithoutFail($id);

        if (empty($product)) {
            return $this->fail(-1, 'Product not found');
        }

        $product->delete();

        return $this->success($id, 'Product deleted successfully');
    }
}
